
package net.tycmc.cty.ctyms.timejob.iems.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tycmc.bulb.common.dao.IBaseDAO;
import net.tycmc.bulb.common.dao.ITransactionDAO;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.cty.ctyms.timejob.common.DateControl;
import net.tycmc.cty.ctyms.timejob.common.DateList;

import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MtnForstConn {
	IBaseDAO baseDAO;
	public IBaseDAO getBaseDAO() {
		return baseDAO;
	}


	public void setBaseDAO(IBaseDAO baseDAO) {
		this.baseDAO = baseDAO;
	}


	public ITransactionDAO getTranDAO() {
		return tranDAO;
	}


	public void setTranDAO(ITransactionDAO tranDAO) {
		this.tranDAO = tranDAO;
	}


	private ITransactionDAO tranDAO;
	/**
	 * 车辆定时预测保养计划方法
	 * 
	 */
	public boolean mtnForstShowTime() {
		
		try {
			System.out.println("保养预测开始~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			//所有车辆信息
			List<Map<String,Object>> VehicleInfoList = this.getVehicleInfoList();
			if(VehicleInfoList != null && VehicleInfoList.size() > 0){
				//循环所有车辆信息
				for(int i = 0; i < VehicleInfoList.size(); i++){
					//单个车辆信息
					Map<String,Object> VehicleInfo = VehicleInfoList.get(i);			
					//最新保养记录
					Map<String,Object> MtnInfo = this.getMtnInfo(VehicleInfo.get("VehicleID")+"");			
					//查询出该机型的保养标准信息
					List<Map<String,Object>> StandardList = this.getStandardList(VehicleInfo.get("VehicleTypeID")+"");
					
					if(StandardList != null && StandardList.size() > 0){
						for(int j = 0; j < StandardList.size(); j++){
							Map<String,Object> Standard = StandardList.get(j);
							//保养方式（1：工作小时数；2：公里数；3：固定时间间隔）
							String MtnType = Standard.get("MtnFS_MtnType")!=null?Standard.get("MtnFS_MtnType").toString():"";
							//调用预测方法
							if(MtnType.equals("1")){
								this.calculate(MtnInfo,Standard,VehicleInfo);
							}else if(MtnType.equals("2")){
								this.calculateKm(MtnInfo, Standard, VehicleInfo);
							}else if(MtnType.equals("3")){
								this.calculateDays(MtnInfo, Standard, VehicleInfo);
							}
						}
					}
				}
			}
			System.out.println("保养预测结束~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(" 董少辉 类："+this.getClass().getName()+"" +
			" 方法:mtnForstShowTime 执行:车辆定时预测保养计划方法 发生异常");
			return false;
		} 
		
	}
	
	
	/**
	 * 方法说明：查询车辆最新信息
	 * 
	 */
	public List<Map<String,Object>> getVehicleInfoList() {
		//统计日期
		String tableDate = DateUtil.addDay(-1);
		String strSQL = "select top 1 convert(varchar(10),MsgSTP_StatTime,120) MsgSTP_StatTime " +
				"from Message_Stat_TimingParam " +
				"where MsgSTP_StatTime=? order by MsgSTP_StatTime desc";
		Map<String,Object> map = baseDAO.execQueryOne(strSQL, new Object[]{tableDate});
		
		String tmpDate = "";
		if(map.get("MsgSTP_StatTime")!=null)tmpDate = map.get("MsgSTP_StatTime").toString();
		if(tmpDate.equals(""))return null;
		
		StringBuffer strBuff = new StringBuffer();
		strBuff.append("select vvi.VehicleID,vvi.VehicleNumber,vvi.VehicleNo,vvi.VehicleTypeID,ISNULL(MsgSTP_tEWorkHours,0) tEWorkHours,");
		strBuff.append("case VehicleRumKmID when 1 then MsgSTP_tMeterDistance when 2 then MsgSTP_tRunKmExact ");
		strBuff.append("when 3 then MsgSTP_tRunKm when 4 then MsgSTP_tRunKmECU when 5 then MsgSTP_tGPSDistance else MsgSTP_tMeterDistance end ETDistance,VehicleRumKmID ");
		strBuff.append("from V_VehicleInfo vvi left join ");
		strBuff.append("Message_Stat_TimingParam on MsgSTP_VclID=vvi.VehicleID and MsgSTP_StatTime=? where vvi.UsefulLife>=GETDATE() and Tmnl_SoftEdition is not null;");
		
		return baseDAO.execQuery(strBuff.toString(), new Object[]{tmpDate});
	}
	
	/**
	 * 预测车辆下次保养并保存预测计划信息
	 * 
	 * @return
	 */
	private boolean calculate(Map<String,Object> MtnInfo,Map<String,Object> Standard,Map<String,Object> VehicleInfo) {
		
		Float outHours = 0f;
		Float everydayWorkHours = 0f;
		
		outHours = Float.parseFloat(this.getSys_ParmConfig().get("SysPC_MtnInHours")+"");
		outHours = outHours == null?2000f:outHours;
		everydayWorkHours = Float.parseFloat(this.getSys_ParmConfig().get("SysPC_DayWorkTime")+"");
		everydayWorkHours = everydayWorkHours == null?18f:everydayWorkHours;
		
		//工作小时数		
		float tEWorkHours = 0;
		//上次保养小时数
		float MtnR_WorkTime = 0;	
		//保养间隔小时数
		float KeepRuleHour = 0;
		
		
		try {
			if(VehicleInfo.get("tEWorkHours")== null){
				return false;
			}
			tEWorkHours = Float.parseFloat(VehicleInfo.get("tEWorkHours")+"");					
			if(tEWorkHours < outHours){
				if(Standard.get("MtnFS_MtnInHours")!=null){
					KeepRuleHour = Float.parseFloat(Standard.get("MtnFS_MtnInHours")+"");					
				}
			}else{
				if(Standard.get("MtnFS_MtnOutHours")!=null){
					KeepRuleHour = Float.parseFloat(Standard.get("MtnFS_MtnOutHours")+"");					
				}
			}
			//保养间隔小时数不能等于0
			if(KeepRuleHour == 0){
				return false;
			}
			if(MtnInfo != null){
				//如果上次保养小时数为0
				if(MtnInfo.get("MtnR_WorkTime") == null){
					int beiShu = (int)(tEWorkHours/KeepRuleHour);
					MtnR_WorkTime=beiShu*KeepRuleHour;
				}else{
					MtnR_WorkTime = Float.parseFloat(MtnInfo.get("MtnR_WorkTime")+"");
				}
			}else{
				int beiShu = (int)(tEWorkHours/KeepRuleHour);
				MtnR_WorkTime=beiShu*KeepRuleHour;
			}
			
			
			int days = 0;
			float nextHour=MtnR_WorkTime+KeepRuleHour;
			
			HashMap<String, String> hm = null;
			
			for(int i = 1; i < 9999; i++){
				nextHour=MtnR_WorkTime+KeepRuleHour*i;
				days =(int)((nextHour-tEWorkHours)/everydayWorkHours);
				//days =days > 1?days + 1:days;
				if(days <= 62){
					hm = new HashMap<String, String>();
					hm.put("MtnF_VclT_ID", VehicleInfo.get("VehicleTypeID")+"");//机型ID
					hm.put("MtnF_Vcl_ID", VehicleInfo.get("VehicleID")+"");//机械ID			
					hm.put("MtnF_MtnFS_ID", Standard.get("MtnFS_ID")+"");//保养标准ID		
					hm.put("MtnF_ForstWorkTime", nextHour+"");//预计保养工作小时数
					hm.put("days", days+"");// 距下次保养天数（用于计算预计保养时间）
					hm.put("tEWorkHours", tEWorkHours+"");
					this.saveMtnForstWorkTime(hm);
				}else{
					break;
				}
			}
		    return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(" 董少辉 类："+this.getClass().getName()+"" +
			" 方法:calculate 执行:预测车辆下次保养并保存预测计划信息方法 发生异常");
			return false;
		} 
	}
	/**
	 * 按设备行驶公里数预测车辆下次保养并保存预测计划信息
	 * @param MtnInfo
	 * @param Standard
	 * @param VehicleInfo
	 * @return
	 */
	private boolean calculateKm(Map<String,Object> MtnInfo,Map<String,Object> Standard,Map<String,Object> VehicleInfo) {
		//保内行驶公里数标准
		Float outKm = 0f;
		Object SysPC_MtnInKm = this.getSys_ParmConfig().get("SysPC_MtnInKm");
		outKm = SysPC_MtnInKm!=null&&!"".equals(SysPC_MtnInKm)?Float.parseFloat(SysPC_MtnInKm+""):2000f;
		//日均行驶公里数
		Float dayRunKm = 0f;
		Object SysPC_DayRunKm = this.getSys_ParmConfig().get("SysPC_DayRunKm");
		dayRunKm = SysPC_DayRunKm!=null&&!"".equals(SysPC_DayRunKm)?Float.parseFloat(SysPC_DayRunKm+""):1080f;
		
		//行驶公里数		
		float tKm = 0;
		//上次保养公里
		float MtnR_WorkKm = 0;	
		//保养间隔公里数
		float KeepRuleKm = 0;
		
		
		try {
			if(VehicleInfo.get("ETDistance")== null){
				return false;
			}
			tKm = Float.parseFloat(VehicleInfo.get("ETDistance")+"");
			if(tKm < outKm){
				if(Standard.get("MtnFS_MtnInKm")!=null){
					KeepRuleKm = Float.parseFloat(Standard.get("MtnFS_MtnInKm")+"");					
				}
			}else{
				if(Standard.get("MtnFS_MtnOutKm")!=null){
					KeepRuleKm = Float.parseFloat(Standard.get("MtnFS_MtnOutKm")+"");					
				}
			}
			//保养间隔公里数不能等于0
			if(KeepRuleKm == 0){
				return false;
			}
			if(MtnInfo != null){
				//如果上次保养公里数为0
				if(MtnInfo.get("MtnR_RunKm") == null){
					int beiShu = (int)(tKm/KeepRuleKm);
					MtnR_WorkKm = beiShu*KeepRuleKm;
				}else{
					MtnR_WorkKm = Float.parseFloat(MtnInfo.get("MtnR_RunKm")+"");
				}
			}else{
				int beiShu = (int)(tKm/KeepRuleKm);
				MtnR_WorkKm = beiShu*KeepRuleKm;
			}
			
			
			int days = 0;
			float nextKm=MtnR_WorkKm+KeepRuleKm;
			HashMap<String, String> hm = null;
			
			for(int i = 1; i < 9999; i++){
				nextKm=MtnR_WorkKm+KeepRuleKm*i;
				days = (int)((nextKm-tKm)/dayRunKm);
//				days =days > 1?days + 1:days;
				if(days <= 62){
					hm = new HashMap<String, String>();
					hm.put("MtnF_VclT_ID", VehicleInfo.get("VehicleTypeID")+"");//机型ID
					hm.put("MtnF_Vcl_ID", VehicleInfo.get("VehicleID")+"");//机械ID	
					hm.put("MtnF_RunKMID", VehicleInfo.get("VehicleRumKmID")+"");//所用里程类型
					hm.put("MtnF_MtnFS_ID", Standard.get("MtnFS_ID")+"");//保养标准ID
					hm.put("MtnF_ForstRunKm", nextKm+"");//预计保养公里
					hm.put("days", days+"");// 距下次保养天数（用于计算预计保养时间）
					hm.put("tEWorkHours", VehicleInfo.get("tEWorkHours")!=null?VehicleInfo.get("tEWorkHours").toString():"0");
					this.saveMtnForstKm(hm);
				}else{
					break;
				}
			}
		    return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(" 董少辉 类："+this.getClass().getName()+"" +
			" 方法:calculate 执行:按设备行驶公里数预测车辆下次保养并保存预测计划信息方法 发生异常");
			return false;
		} 
	}
	
	/**
	 * 保养预测--按固定时间间隔
	 * @param MtnInfo
	 * @param Standard
	 * @param VehicleInfo
	 * @return
	 */
	private boolean calculateDays(Map<String,Object> MtnInfo,Map<String,Object> Standard,Map<String,Object> VehicleInfo) {
		
		//保养间隔天数
		String MtnFS_MtnGapDays = MapGetter.getString(Standard, "MtnFS_MtnGapDays");
		int MtnGapDays = Integer.parseInt(MtnFS_MtnGapDays);
		//上次保养日期
		String MtnR_CloseTime = MapGetter.getString(MtnInfo, "MtnR_CloseTime");
		if(!StringUtil.isValid(MtnR_CloseTime)){
			return false;
		}
		//当前日期距上次保养日期间隔
		int gapDays = DateControl.getGapDays(MtnR_CloseTime);
		try {
			
			int days = 1;
			//距上次保养间隔天数
			int nextDays = 0;
			
			HashMap<String, String> hm = null;
			
			for(int i = 1; i < 9999; i++){
				nextDays = MtnGapDays*i;
				days = nextDays-gapDays;
				if(days <= 62){
					hm = new HashMap<String, String>();
					hm.put("MtnF_VclT_ID", VehicleInfo.get("VehicleTypeID")+"");//机型ID
					hm.put("MtnF_Vcl_ID", VehicleInfo.get("VehicleID")+"");//机械ID			
					hm.put("MtnF_MtnFS_ID", Standard.get("MtnFS_ID")+"");//保养标准ID		
					hm.put("MtnF_GapDays", nextDays+"");//距离上次保养间隔天数
					hm.put("days", days+"");// 距下次保养天数（用于计算预计保养时间）
					hm.put("tEWorkHours", VehicleInfo.get("tEWorkHours")!=null?VehicleInfo.get("tEWorkHours").toString():"0");
					this.saveMtnForst(hm);
				}else{
					break;
				}
			}
		    return true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(" LXF 类："+this.getClass().getName()+"" +
			" 方法:calculate 执行:预测车辆下次保养（按固定时间间隔）并保存预测计划信息方法 发生异常");
			return false;
		} 
	}
	
	/**
	 * 保养计划添加--工作小时
	 * dsh
	 * @param hm
	 * @return
	 * @throws Exception 
	 */
	private int saveMtnForstWorkTime(HashMap<String, String> hm) throws Exception {
		String sql = "INSERT INTO MtnForst_Info(MtnF_ForstTime," +
				"MtnF_ForstTimeEnd,MtnF_VclT_ID,MtnF_Vcl_ID," +
				"MtnF_MtnFS_ID,MtnF_ForstWorkTime,MtnF_MtnDate,MtnF_tEWorkHours) " +
				"VALUES (convert(varchar(10),GETDATE(),126),'"+DateList.addDay(DateList.dateToString(new Date(),"yyyy-MM-dd"), 62)+"',"+hm.get("MtnF_VclT_ID")
				+","+hm.get("MtnF_Vcl_ID")+","+hm.get("MtnF_MtnFS_ID")+","+hm.get("MtnF_ForstWorkTime")+",GETDATE()+"+hm.get("days")
				+","+hm.get("tEWorkHours")+")";
		return baseDAO.execInsert(sql, new Object[]{});
	}
	
	/**
	 * 保养计划添加--固定时间间隔
	 * dsh
	 * @param hm
	 * @return
	 * @throws Exception 
	 */
	private int saveMtnForst(HashMap<String, String> hm) throws Exception {
		String sql = "INSERT INTO MtnForst_Info(MtnF_ForstTime," +
				"MtnF_ForstTimeEnd,MtnF_VclT_ID,MtnF_Vcl_ID," +
				"MtnF_MtnFS_ID,MtnF_ForstWorkTime,MtnF_MtnDate,MtnF_tEWorkHours,MtnF_GapDays) " +
				"VALUES (convert(varchar(10),GETDATE(),126),'"+DateList.addDay(DateList.dateToString(new Date(),"yyyy-MM-dd"), 62)+"',"+hm.get("MtnF_VclT_ID")
				+","+hm.get("MtnF_Vcl_ID")+","+hm.get("MtnF_MtnFS_ID")+","+hm.get("MtnF_ForstWorkTime")+",GETDATE()+"+hm.get("days")
				+","+hm.get("tEWorkHours")+","+MapGetter.getString(hm, "MtnF_GapDays")+")";
		return baseDAO.execInsert(sql, new Object[]{});
	}
	/**
	 * 保养计划添加-公里
	 * @param hm
	 * @return
	 * @throws Exception
	 */
	private int saveMtnForstKm(HashMap<String, String> hm) throws Exception {
		String sql = "INSERT INTO MtnForst_Info(MtnF_ForstTime," +
				"MtnF_ForstTimeEnd,MtnF_VclT_ID,MtnF_Vcl_ID," +
				"MtnF_MtnFS_ID,MtnF_ForstRunKm,MtnF_MtnDate,MtnF_tEWorkHours,MtnF_RunKMID ) " +
				"VALUES (convert(varchar(10),GETDATE(),126),'"+DateList.addDay(DateList.dateToString(new Date(),"yyyy-MM-dd"), 62)+"',"+hm.get("MtnF_VclT_ID")+","+hm.get("MtnF_Vcl_ID")+","+hm.get("MtnF_MtnFS_ID")+","+hm.get("MtnF_ForstRunKm")+",GETDATE()+"+hm.get("days")+","+hm.get("tEWorkHours")+","+hm.get("MtnF_RunKMID")+")";
		return baseDAO.execInsert(sql, new Object[]{});
	}
	
	
	/**
	 *方法说明：根据机型ID 查询保养标准
	 * dsh
	 * 2011-10-7 10:18:47
	 */
	public List<Map<String,Object>> getStandardList(String MtnFS_VclT_ID){
		String sql = "select MtnForst_Standard.MtnFS_ID,MtnForst_Standard.MtnFS_VclT_ID,Sys_MtnType.SysMT_Type," +
				"MtnForst_Standard.MtnFS_MtnInHours,MtnForst_Standard.MtnFS_MtnOutHours,MtnForst_Standard.MtnFS_MtnInKm," +
				"MtnForst_Standard.MtnFS_MtnOutKm,MtnForst_Standard.MtnFS_MtnType,MtnForst_Standard.MtnFS_Eff,MtnForst_Standard.MtnFS_Exp, " +
				"MtnFS_MtnGapDays " +
				"from MtnForst_Standard left join Sys_MtnType on MtnForst_Standard.MtnFS_SysMT_ID= Sys_MtnType.SysMT_ID where " +
				"convert(varchar(10),MtnFS_Eff,126) <= getdate() and convert(varchar(10),MtnFS_Exp,126) >= getdate() and MtnFS_VclT_ID = ?";
			return baseDAO.execQuery(sql, new Object[]{MtnFS_VclT_ID});
	}
	
	/**
	 *方法说明：根据车辆ID 查询保养记录
	 * dsh
	 * 2011-10-7 10:18:47
	 */
	public Map<String,Object> getMtnInfo(String MtnR_Vcl_ID){
		String sql = "select MAX(MtnR_WorkTime) MtnR_WorkTime,MAX(MtnR_RunKm) MtnR_RunKm,MAX(MtnR_CloseTime) MtnR_CloseTime " +
				"from MtnRepair_Info left join Sys_MtnRepType on MtnRepair_Info.MtnR_SysMRT_ID = Sys_MtnRepType.SysMRT_ID where " +
				"convert(varchar(10),MtnR_Eff,126) <= getdate() and convert(varchar(10),MtnR_Exp,126) > getdate() " +
				"and MtnR_Vcl_ID =? and Sys_MtnRepType.SysMRT_ID=2 " +
				"and convert(varchar(10),SysMRT_Eff,126) <= getdate() " +
				"and convert(varchar(10),SysMRT_Exp,126) > getdate()";
			return baseDAO.execQueryOne(sql, new Object[]{MtnR_Vcl_ID});
	}
	
	
	/**
	 *方法说明： 查询保养参数信息
	 * dsh
	 * 2011-10-7 10:18:47
	 */
	public Map<String,Object> getSys_ParmConfig(){
		String sql = "SELECT SysPC_ID,SysPC_MtnAlarmHours,SysPC_Month_Bgn,SysPC_Month_End,SysPC_Remark,SysPC_MtnInHours,SysPC_DayWorkTime,SysPC_MtnInKm,SysPC_MtnAlarmKm,SysPC_DayRunKm FROM Sys_ParmConfig";
		return baseDAO.execQueryOne(sql, new Object[]{});
	}
	
	public static void main(String[] args) throws Exception{
		ApplicationContext ctx = null;
		ctx = new ClassPathXmlApplicationContext(new String[] {
				"applicationContext-basedao.xml",
				"applicationContext-generall.xml"});
		JAXPConfigurator.configure("src/proxool.xml", false);
		MtnForstConn mtnForstConn = (MtnForstConn) ctx.getBean("mtnForstConn");
		if (mtnForstConn == null) {
			System.out.println("null");
		}else {
			mtnForstConn.mtnForstShowTime();
		}
	}

}